#include "Channel.h"
#include <assert.h>
#include "Socket.h"
#include "EventLoop.h"
#include "Log.h"

namespace dsth {

const int Channel::kNoneEvent  = 0x00;
const int Channel::kReadEvent  = 0x01;
const int Channel::kWriteEvent = 0x02;
const int Channel::kErrorEvent = 0x04;

Channel::Channel(int fd, EventLoop* loop)
    : fd_(fd),
    loop_ptr_(loop),
    event_(kNoneEvent),
    revent_(kNoneEvent),
    status_(E_NEW) {
    assert(fd_ > 0 && loop_ptr_ != NULL);
}


Channel::~Channel() {
    LOG_DEBUG("[Channel::~Channel]");
}

void Channel::EnableReading() {
    event_ |= kReadEvent;
    loop_ptr_->Update(this);
}

void Channel::EnableWriting() {
    event_ |= kWriteEvent;
    loop_ptr_->Update(this);
}

void Channel::DisableReading() {
    event_ &= ~kReadEvent;
    loop_ptr_->Update(this);
}

void Channel::DisableWriting() {
    event_ &= ~kWriteEvent;
    loop_ptr_->Update(this);
}

void Channel::DisableAllEvent() {
    event_ = kNoneEvent;
    loop_ptr_->Update(this);
}

int Channel::GetSocketFd() { 
    return fd_; 
}

void Channel::HandleEvent(Timestamp recv_time) {
    if (revent_ & Channel::kReadEvent) {
        read_handler_(recv_time);
    }
    if (revent_ & Channel::kWriteEvent) {
        write_handler_();
    }
    if (revent_ & Channel::kErrorEvent) {
        error_handler_();
    }
}

} // namespace
